package com.google.code.whitetask;

import java.util.ArrayList;
import java.util.List;

//TODO If only phrase, not a clause is specified? At least, in my opinion, RuntimeException should be thrown.  
public class Flow {
  List<Clause> clauses = new ArrayList<Clause>();
  
  public Result flow() {
    Context context = new Context();
    
    for (Clause each : clauses) {
      Result result = each.getTask().execute(context);
      context.setLastResult(result);
      context.setLastTask(each.getTask());
    }
    
    return Result.SUCCESS;
  }

  public Clause execute(Task task) {
    Clause result = new Clause(task);
    clauses.add(result);
    return result;
  }

  public Clause execute(Task ... tasks) {
    Clause result = new Clause(new ChainTask(tasks));
    clauses.add(result);
    return result;
  }
  
  public ParallelExecutionClause executeParallelly(Task ...tasks) {
    ParallelExecutionClause result = new ParallelExecutionClause(new ParallelChainTask(tasks));
    clauses.add(result);
    return result;
  }

  public ParallelExecutionClause executeParallelly(List<Task> tasks) {
    ParallelExecutionClause result = new ParallelExecutionClause(new ParallelChainTask(tasks));
    clauses.add(result);
    return result;
  }

  public ActionPhrase ifLastResultIs(Result result) {
    return new ActionPhrase(this, result);
  }
}
